import { Menu } from "antd";
import { createFromIconfontCN } from '@ant-design/icons';
import React from "react";
const { SubMenu, Item } = Menu;
const Icon = createFromIconfontCN({
    scriptUrl: '//at.alicdn.com/t/font_2525320_juckds754e.js', // 在 iconfont.cn 上生成
});

class UserMenu extends React.Component {
    constructor() {
        super()
        this.state = {
            openKeys: [],
            isMenuClick: false
        }
    }

    creatMenus(menu = []) {
        if (Array.isArray(menu)) {
            // 返回遍历后的ui数组
            return menu.map(item => {
                // 如果父路由有children属性
                if (item.children) {
                    // 则返回生成一个子级菜单
                    return (
                        <SubMenu key={item.path} icon={<Icon type={item.meta.icon} />} title={item.meta.title}>
                            {/* 递归生成 */}
                            {this.creatMenus(item.children)}
                        </SubMenu>
                    )
                }
                // 没有children属性则值渲染一级菜单
                return <Item key={item.path} icon={<Icon type={item.meta.icon} />} onClick={() => {
                    this.props.jump.history.push(item.path)
                }}> {item.meta.title}</Item >
            })
        }
    }

    // submenu打开关闭时触发
    handleOpenChange(openKeys) {
        this.setState({
            openKeys,
            isMenuClick: true
        })
    }

    static getDerivedStateFromProps(nextProps, nextState) {
        let { isMenuClick, openKeys } = nextState;
        // 判断，如果用户是点击时
        if (isMenuClick) {
            // 直接返回原数组，并把点击判断更改为false
            return {
                openKeys,
                isMenuClick: false
            }
        } else {
            // 如果是更改路径，那么截取多级路由的一级路径
            let { pathname } = nextProps.jump.location;
            let keys = pathname.split("/");
            return {
                openKeys: ["/" + keys[1]]
            }
        }
    }

    render() {
        // 动态获取选中当前菜单项，配合selectedKeys属性显示高亮
        let { pathname } = this.props.jump.location;
        let { openKeys } = this.state;
        let keys = pathname.split("/");

        // 把渲染菜单解构并递归渲染出来
        let { menus } = this.props;
        return (
            <Menu theme="dark" mode="inline" selectedKeys={[pathname]} openKeys={openKeys} onOpenChange={this.handleOpenChange.bind(this)}>
                {/* 调用 */}
                {this.creatMenus(menus)}
            </Menu>
        )
    }
}

export default UserMenu;